package org.sraosha.framework.helper;

import ch.qos.logback.core.Context;
import ch.qos.logback.core.spi.PropertyDefiner;
import ch.qos.logback.core.status.Status;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml;

import java.util.Map;

/**
 * logback自定义属性，用于在日志文件名中显示端口
 */
@Component
public class LogbackHelper implements PropertyDefiner {

    /**
     * 端口参数
     */
    private static final String LOGBACK_PORT_PARAMETER = "--server.port";

    /**
     * 端口号
     */
    public static String logbackPort;

    /**
     * 默认配置文件名
     */
    private static String yml = "bootstrap.yml";

    /**
     * 覆盖配置文件名
     * @param newYml
     */
    public static void setYml(String newYml){
        yml = newYml;
    }

    /**
     * 返回端口
     * @return
     */
    @Override
    public String getPropertyValue() {
        if (null == logbackPort){
            Yaml yaml = new Yaml();
            Map<String, Object> serverMap = yaml.load(LogbackHelper.class.getResourceAsStream("/" + yml));
            Map<String, Object> portMap = (Map<String, Object>) serverMap.get("server");
            Integer port = (Integer) portMap.get("port");
            return port.toString();
        }else {
            return logbackPort;
        }
    }

    @Override
    public void setContext(Context context) {

    }

    @Override
    public Context getContext() {
        return null;
    }

    @Override
    public void addStatus(Status status) {

    }

    @Override
    public void addInfo(String msg) {

    }

    @Override
    public void addInfo(String msg, Throwable ex) {

    }

    @Override
    public void addWarn(String msg) {

    }

    @Override
    public void addWarn(String msg, Throwable ex) {

    }

    @Override
    public void addError(String msg) {

    }

    @Override
    public void addError(String msg, Throwable ex) {

    }

    /**
     * 当启动两个进程时，使用--server.port指定端口号。这个端口号会放在日志文件名中。
     */
    public static void setLogbackPort(String[] args){
        if (args.length > 0){
            for (String arg : args){
                String[] paramArray = arg.split("=");
                if (paramArray.length > 1){
                    String key = paramArray[0];
                    String value = paramArray[1];
                    if (LOGBACK_PORT_PARAMETER.equals(key)){
                        logbackPort = value;
                        break;
                    }
                }
            }
        }
    }
}
